package com.shang.proxy;

import com.shang.dao.UserDao;
import com.shang.dao.UserDaoImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @ClassName JDKProxy
 * @Description TODO
 * @Author Larry
 * @Date 2021/5/20 13:51
 * @Version 1.0
 */
public class JDKProxy {

    public static void main(String[] args) {

        Class[] interfaces = {UserDao.class};
        UserDaoImpl userDaoImpl = new UserDaoImpl();
        UserDao userDao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new MyProxy(userDaoImpl));
        int add = userDao.add(1, 2);
        System.out.println(add);
    }
}

class MyProxy implements InvocationHandler {

    private Object obj;

    public MyProxy(Object obj) {
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("方法执行之前..........." + method.getName() + Arrays.toString(args));

        Object invoke = method.invoke(obj, args);

        System.out.println("方法执行之后.........................");

        return invoke;
    }
}